package org.lk.reggie.filter;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.lk.reggie.common.BaseContext;
import org.lk.reggie.common.R;
import org.lk.reggie.entity.Employee;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 检查用户是否已经登录
 */
@WebFilter(filterName = "loginCheckFilter", urlPatterns = "/*")
@Slf4j
public class LoginCheckFilter implements Filter
{
    // 路径匹配器，支持通配符
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException
    {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        String requestURI = request.getRequestURI();

        String curOrigin = request.getHeader("Origin");
//        response.setHeader("Access-Control-Allow-Origin", curOrigin == null ? "true" : curOrigin);
//        response.setHeader("Access-Control-Allow-Credentials", "true");
//        response.setHeader("Access-Control-Allow-Methods", "POST, GET, PATCH, DELETE, PUT");
//        response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");

        log.info("本次请求的路径:{}", requestURI);

        // 不需要处理的请求
        String[] urls = {
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/user/sendMsg",
                "/user/login"
        };

        // 判断本次请求是否需要处理
        boolean check = check(requestURI,urls);

        if (check)
        {
            log.info("本次请求 {} 不需处理！", requestURI);
            filterChain.doFilter(request,response);
        }
        else
        {
            if(request.getSession().getAttribute("employee") != null)
            {
                log.info("用户 {} 已登录", request.getSession().getAttribute("employee"));
                Long employeeId = (Long) request.getSession().getAttribute("employee");
                BaseContext.setCurrentId(employeeId);
                filterChain.doFilter(request,response);
                return;
            }

            if(request.getSession().getAttribute("user") != null)
            {
                log.info("用户 {} 已登录", request.getSession().getAttribute("user"));
                Long userId = (Long) request.getSession().getAttribute("user");
                BaseContext.setCurrentId(userId);
                filterChain.doFilter(request,response);
                return;
            }


            log.info("用户/员工未登录！");
            response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        }
    }


    /**
     * 路径匹配，检查本次请求是否需要放行
     * @param requestURI
     * @return
     */
    public boolean check(String requestURI, String[] urls)
    {
        for (String path: urls)
        {
            boolean match = PATH_MATCHER.match(path, requestURI);
            if (match)
            {
                return true;
            }
        }
        return false;
    }




}
